import axios from 'axios'
import { message } from "ant-design-vue";
import router from './../router'
import config from './../config'
//import storage from './../utils/storage'
//import { STORAGE } from './../constants'
const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERR = '网络异常'
import storage from "@/utils/storage"
import pinia from '@/stores/store'
import { useLoginStore } from "@/stores/loginConfig";
const systemDataStore = useLoginStore(pinia);
const { changeLoginData } = systemDataStore
message.config({
  maxCount: 1,
})
function readerRes(res) {
  return new Promise((resolve, reject) => {
    let data = {};
    let reader = new FileReader();
    // 读取文件内容
    reader.readAsText(res, 'utf-8');
    // 处理文件读取完成事件
    reader.onload = (e) => {
      try {
        data = JSON.parse(e.target.result);
      } catch (error) {
      }
      if (data?.code === 500) {
        // 处理错误状态
        resolve({
          code: 500,
          errorMsg: data.errorMsg
        });
      } else {
        // 正常状态
        resolve(res);
      }
    };
    // 处理文件读取错误
    reader.onerror = (error) => {
      console.error('File reading error:', error);
    };
  });
}
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

//创建axios实例对象，添加全局配置
const service = axios.create({
  baseURL: config.baseApi,
  timeOut: 8000,
  showloading: true
})
//请求拦截
service.interceptors.request.use((req) => {
  const headers = req.headers;
  headers.from = 'Y'
  // const { access_token = "" } = storage.getItem(STORAGE.TOKEN) || {};
  const basic_token = 'bmdwOm5ncA=='
  const access_token = ''
  // if (!access_token) router.push('/login')
  // if (!headers.Authorization && access_token) {
  const userInf = storage.getItem("USER_INFO")
  if (req.url === '/api/base/oauth2/token') {
    req.headers.Authorization = 'Basic ' + basic_token;
  } else if (userInf && Object.keys(userInf).length > 0 && 'access_token' in userInf) {
    req.headers.Authorization = 'Bearer ' + userInf.access_token;
  } else {
    router.push('/login')
  }

  // req.headers.Cookie = 'JSESSIONID=FRrbI6168iZllHpNApY6hbcOAAKRHuDE4-klCZ0Q';
  // }

  // if (req.showloading) {
  //   showFullScreenLoading()
  // }

  return req;
})
//响应拦截
service.interceptors.response.use(async (res) => {
  const { code, data, msg } = res.data

  if (res.config.url === '/api/base/oauth2/token') {
    return res.data
  }
  if (code === 0) {
    return {
      code: code,
      data: data
    }
  } else if (code == 1) {
    console.log('msg', msg)
    // todo:暂时拦截报错
    if (!msg.includes('finishConnect')) {
      message.error(msg || NETWORK_ERR)
    }
    // message.error(msg || NETWORK_ERR)
    return {
      code: code,
      data: data,
      msg: msg
    }
  } else {
    if (res.config.responseType === 'blob') {
      // return res.data 原来的代码中，blob是直接返回
      let data = await readerRes(res.data || res)
      return data
    } else if (code == -250721){
      // 该厂商无相关点位，无法渲染这个点位数据，给个提示
      message.warning('该厂商无相关点位，暂不支持展示', 5)
    } else {
      return Promise.reject(msg || NETWORK_ERR)
    }
  }

}, (error) => {
  if (error.status == 424) {
    changeLoginData({})
    router.push('/login')
    return Promise.reject(TOKEN_INVALID)
  } else {
    const errMsg = error.response?.data?.msg || NETWORK_ERR
    message.error(errMsg)
  }
})
function request(options) {
  options.method = options.method || 'get'
  options.responseType = options.responseType || ''
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }
  if (config.env === 'prod') {
    service.defaults.baseURL = config.baseApi
  } else {
    service.defaults.baseURL = config.baseApi
  }
  return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({
      url,
      data,
      method: item,
      responseType,
      ...options
    })
  }
})
export default request